package com.jushu.storbox.adapter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.FileDownloadActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.callback.IDownloadThumbnailCallback;
import com.jushu.storbox.callback.IShareDownloadCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.fragment.ShareFragment;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.image.BitmapUtil;
import com.jushu.storbox.view.dialog.ClouddriveDialog;

public class ShareFileAdapter extends BaseAdapter {
	private Context context;

	private LayoutInflater mInflater;

	private List<FileFolderInfo> resource;

	private ShareFragment shareFragment;

	private ICloudDriveService shareDriveService;

	private ProgressBar downlonProgressBar;

	private ClouddriveDialog dialog;

	private Handler handler;

	private SimpleDateFormat timeDateFormat;

	private String timeInfo;

	private String path;

	private String lastPath;

	private String TAG = "SharedFileAdapter";

	String shareId = "";

	int isInode = -1;

	public ShareFileAdapter(ShareFragment shareFragment, Context context, List<FileFolderInfo> resource, ICloudDriveService shareDriveService, Handler handler) {
		// Auto-generated constructor stub
		this.context = context;
		this.resource = resource;
		this.shareDriveService = shareDriveService;
		this.handler = handler;
		this.shareFragment = shareFragment;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		timeDateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm");
	}

	@Override
	public int getCount() {
		return resource.size();
	}

	@Override
	public FileFolderInfo getItem(int position) {
		return resource.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		FileFolderInfo fileInformation = getItem(position);
		ViewHolder viewHolder = null;
		if (null == convertView) {
			viewHolder = new ViewHolder();
			convertView = viewHolder.initHolder(convertView);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		viewHolder.setFileFolderInfo(fileInformation);

		fileInformation.setItemView(convertView);

		viewHolder.setFileSize();

		viewHolder.createPath();

		viewHolder.showProgress();

		viewHolder.setDateValue();

		viewHolder.setNameValue();

		viewHolder.setTypeImage();

		viewHolder.setClickListener(position);

		return convertView;
	}

	public class ViewHolder {
		private TextView fileName;

		private TextView date;

		private ImageView typeImg;

		private TextView fileSize;

		private ImageView moreButton;

		private RelativeLayout item_img_re;

		private ProgressDialog downloadDialog;

		private String isDialog = "0";

		private String fileIconPath;

		private FileFolderInfo fileFolderInfo;

		private RelativeLayout item_more_ll;

		private void downlonFileDialog() {
			dialog = new ClouddriveDialog(context, R.style.dialog_upload, R.layout.dialog_download);
			dialog.setCancelable(false);
			View conventView = dialog.getConventView();
			Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_download_file_cancal_bt);
			TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_download_prompt_tv);
			downlonProgressBar = (ProgressBar) conventView.findViewById(R.id.dialog_download_progressbar);
			downlonProgressBar.setMax(100);
			downlonProgressBar.setProgress(0);
			dialog_prompt_tv.setText(context.getString(R.string.fileListadapter_openfileing));

			dialog_cancal.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					isDialog = "0";
				}
			});
			dialog.show();
		}

		private IShareDownloadCallback downloadCallback = new IShareDownloadCallback() {
			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = 5;
				msg.arg1 = 200;
				downloadHandler.sendMessage(msg);
				LogUtil.i(TAG, "download_success");
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				msg.what = 0;
				downloadHandler.sendMessage(msg);
				LogUtil.i(TAG, "download_start");
			}

			@Override
			public void onProgress(int currentProgress, long currentSize, long maxSize) {
				// TODO Auto-generated method stub
				Message msg_download = new Message();
				msg_download.what = 4;
				msg_download.arg1 = 100;
				msg_download.arg2 = currentProgress;
				String size = "";
				if (100 != currentProgress) {
					long tempMax = currentSize / currentProgress;
					size = PublicTools.changeBKM(String.valueOf(currentSize)) + " / " + PublicTools.changeBKM(String.valueOf(tempMax));
				} else {
					size = PublicTools.changeBKM(String.valueOf(currentSize));
				}
				msg_download.obj = size;

				downloadHandler.sendMessage(msg_download);
			}

			@Override
			public void onFailure(Throwable t, int statusCode) {
				// TODO Auto-generated method stub3

				if (statusCode == 401) {
					LogUtil.e(TAG, "get token final");
					// Message msg = new Message();
					// msg.what = ClientConfig.FAILTOOBTAINLIST;
					// msg.obj = statusCode;
					// handler.sendMessage(msg);
				} else {
					Message msg = new Message();
					msg.what = 5;
					msg.arg1 = 400;
					downloadHandler.sendMessage(msg);
					LogUtil.e(TAG, "download_failed");
				}
			}

			@Override
			public void onStop() {
			}

			@Override
			public void onCanceled() {
			}

			@Override
			public void onDettach() {
			}
		};

		private Handler downloadHandler = new Handler() {
			public void handleMessage(Message msg) {
				// download file
				switch (msg.what) {
				case 0:
					// pinProgressButton.setVisibility(View.VISIBLE);
					// progressSharedAbove.setVisibility(View.VISIBLE);
					// pinProgressButton.setMax(100);
					// pinProgressButton.setProgress(100);
					// updatePinProgressContentDescription(pinProgressButton);
					// pinProgressButton.setVisibility(View.VISIBLE);
					// pinProgressButton.setMax(100);
					// pinProgressButton.setProgress(msg.arg2);
					// updatePinProgressContentDescription(pinProgressButton);
					break;
				case 1:
					// downloading...
					// pinProgressButton.setVisibility(View.VISIBLE);
					// pinProgressButton.setMax(msg.arg1);
					// pinProgressButton.setProgress(msg.arg2);
					// updatePinProgressContentDescription(pinProgressButton);
					if (msg.arg1 == msg.arg2) {
						if (null != downloadDialog && downloadDialog.isShowing()) {
							downloadDialog.dismiss();
						}
						// PublicTools.openFile(context, filePath);
						// dialog.cancel();
					}

					// start download
					// if(isBounceDialog && isDialog.equals("isDialog")){
					// downlonFileDialog();
					// //
					// downlonProgressBar.setHorizontalScrollBarEnabled(true);
					// isBounceDialog = false;
					// }
					break;
				case 7:
					// download fail
					if (null != downloadDialog && downloadDialog.isShowing()) {
						downloadDialog.dismiss();
					}
					if (null != dialog) {
						dialog.dismiss();
					}
					// Toast.LENGTH_SHORT).show();
				case 3:// begin download
					downloadDialog = new ProgressDialog(context);
					downloadDialog.setMessage(context.getString(R.string.main_activity_update_now_download));
					if (null != downloadDialog && (!downloadDialog.isShowing())) {
						downloadDialog.show();
					}
					break;
				case 4:// downloading
					if (msg.arg1 == 100 && msg.arg2 > -1) {
						// pinProgressButton.setVisibility(View.VISIBLE);
						// progressSharedAbove.setVisibility(View.VISIBLE);
						// pinProgressButton.setMax(msg.arg1);
						// pinProgressButton.setProgress(msg.arg2);
						// updatePinProgressContentDescription(pinProgressButton);
						fileSize.setText((String) msg.obj);
					}
					if (isDialog.equals("isDialog")) {// confirm dialog
						if (msg.arg2 > -1) {
							downlonProgressBar.setProgress(msg.arg2);
						}
					}
					break;
				case 5://
					if (null != downloadDialog && (downloadDialog.isShowing())) {
						downloadDialog.dismiss();
					}
					if (200 == msg.arg1) {
						if (null != dialog) {
							dialog.dismiss();
						}
						iFileManager mdmTools = FileManagerFactory.getFileManager(context);
						if (isDialog.equals("isDialog")) {
							dialog.cancel();
							if (mdmTools.fileIsExist(path)) {
								mdmTools.openFile(path, fileFolderInfo.getSize());
							}
							isDialog = "0";
						}
					}
					if (400 == msg.arg1) {
						if (null != dialog) {
							dialog.dismiss();
						}
						Toast.makeText(context, context.getString(R.string.fileListadapter_keep_failed), Toast.LENGTH_SHORT).show();
					}
					break;
				case 12:
					new Thread(new Runnable() {
						@Override
						public void run() {
							Bitmap bmp = BitmapUtil.readBitMapFromFile(context, fileIconPath);
							ShareDriveApplication.getInstance().addSharedBitmaps(bmp);
							Message message = new Message();
							message.what = 15;
							message.obj = bmp;
							downloadHandler.sendMessage(message);
						}
					}).start();
					break;
				case 15:
					Bitmap bmp = (Bitmap) msg.obj;
					// LogUtil.i(TAG, "refresh bitmap ui...");
					// typeImg.setBackgroundResource(R.drawable.defaut_icon_img);
					if (null != bmp) {
						typeImg.setImageBitmap(bmp);
					} else {
						LogUtil.e(TAG, "bitmap is null, show default img..." + " | fileIconPath:" + fileIconPath);
					}
					break;
				case 13:
					isDialog = "isDialog";
					downlonFileDialog();

					break;
				}
			};
		};

		IDownloadThumbnailCallback downloadThumbnailCallback = new IDownloadThumbnailCallback() {
			@Override
			public void onSuccess(String fileId) {
				// TODO Auto-generated method stub
				Message msg_download = new Message();
				msg_download.what = 12;
				downloadHandler.sendMessage(msg_download);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgress(int currentProgress, long currentSize, long maxSize) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onFailure(Throwable t) {
				// TODO Auto-generated method stub
				File file = new File(fileIconPath);
				file.delete();
			}
		};

		public View initHolder(View convertView) {
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.item_shared, null);
				fileName = (TextView) convertView.findViewById(R.id.item_name_text);
				date = (TextView) convertView.findViewById(R.id.item_date_text);
				typeImg = (ImageView) convertView.findViewById(R.id.item_type_shared_img);
				moreButton = (ImageView) convertView.findViewById(R.id.item_more_img);
				item_more_ll = (RelativeLayout) convertView.findViewById(R.id.item_more_ll);
				fileSize = (TextView) convertView.findViewById(R.id.item_filelist_file_size);
				item_img_re = (RelativeLayout) convertView.findViewById(R.id.item_img_re);
			}
			return convertView;
		}

		public void setTypeImage() {
			if (fileFolderInfo.getIsFile() == 1) {
				if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.WORD_TYPE)) {
					typeImg.setImageResource(R.mipmap.doc);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.PPT_TYPE)) {
					typeImg.setImageResource(R.mipmap.ppt);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.IMAGE_TYPE)) {
					typeImg.setImageResource(R.mipmap.empty_pic);
					try {
						String iconPath = DirectoryUtil.genSharedThumbnailFullName(context, fileFolderInfo.getId(), fileFolderInfo.getName());
						File thumBnail2 = new File(iconPath);
						fileIconPath = iconPath;
						// if (null == fileInformation.getiNodeId()) {
						if (!thumBnail2.exists() && null != shareDriveService) {
							shareDriveService.downloadShareThumbnailIcon(fileFolderInfo.getOwnerBy(), fileFolderInfo.getiNodeId(), fileFolderInfo.getId(),
									iconPath, downloadThumbnailCallback);
						} else {
							Message msg_download = new Message();
							msg_download.what = 12;
							downloadHandler.sendMessage(msg_download);
						}
					} catch (Exception e) {
						e.printStackTrace();
						LogUtil.e(TAG, "[getTypeImgeID] fileType is image that show fail..." + e.getLocalizedMessage());
					}

				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.RAR_TYPE)) {
					typeImg.setImageResource(R.mipmap.rar);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.ZIP_TYPE)) {
					typeImg.setImageResource(R.mipmap.rar);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.VIDEO_TYPE)) {
					typeImg.setImageResource(R.mipmap.video);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.MUSIC_TYPE)) {
					typeImg.setImageResource(R.mipmap.music);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.TXT_TYPE)) {
					typeImg.setImageResource(R.mipmap.txt);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.PDF_TYPE)) {
					typeImg.setImageResource(R.mipmap.pdf);
				} else if (PublicTools.isFileType(fileFolderInfo.getName(), Constant.EXCEL_TYPE)) {
					typeImg.setImageResource(R.mipmap.excel);
				} else {
					typeImg.setImageResource(R.mipmap.default_file_icon);
				}
			} else {
				typeImg.setImageResource(R.mipmap.folder_im);
			}
		}

		public void setFileSize() {
			if (fileFolderInfo.getIsFile() == 1) {
				String size = PublicTools.changeBKM(fileFolderInfo.getSize() + "");
				fileSize.setText(size);
			} else {
				fileSize.setVisibility(View.GONE);
			}
		}

		public void createPath() {
			iFileManager mdmTools = FileManagerFactory.getFileManager(context);
			if (fileFolderInfo.getIsFile() == 1) {
				String lastPath = DirectoryUtil.generateShareDir(context);
				if (!mdmTools.fileIsExist(lastPath)) {
					mdmTools.createFilePath(lastPath);
				}
			} else {
			}
		}

		public void showProgress() {
			if (fileFolderInfo.getIsFile() == 1) {
				if (fileFolderInfo.isSync() && fileFolderInfo.getTransStatus() == Constant.DOWNLOAD_SUCCESS_UPDATE_DB) {
				}
			} else {
			}
		}

		public void setDateValue() {
			String ownerName = fileFolderInfo.getOwnerName();
			Spanned dateString = null;
			timeInfo = timeDateFormat.format(fileFolderInfo.getModifiedAt());
			if (ownerName != null && !"".equals(ownerName)) {
				ShareDriveApplication.getInstance().setShareOwnerName(ownerName);
				dateString = Html.fromHtml(timeInfo + " by " + "<font color=\"#3282c4\">"
						+ ShareDriveApplication.getInstance().getShareOwnerName().trim().split(" ")[0] + "</font>");
			} else {
				if (null != ShareDriveApplication.getInstance().getShareOwnerName()) {
					dateString = Html.fromHtml(timeInfo + " by " + "<font color=\"#3282c4\">"
							+ ShareDriveApplication.getInstance().getShareOwnerName().trim().split(" ")[0] + "</font>");
				} else {
					dateString = Html.fromHtml(timeInfo);
				}
			}
			date.setText(dateString);
		}

		public void setNameValue() {
			fileName.setText(fileFolderInfo.getName());
		}

		public void setClickListener(final int position) {
			item_more_ll.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					shareFragment.MoreButton(moreButton, position, fileFolderInfo);
				}
			});

			item_img_re.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View arg0) {
					FileFolderInfo cloneOfFileFolderInfo;
					try {
						cloneOfFileFolderInfo = (FileFolderInfo) fileFolderInfo.clone();
						cloneOfFileFolderInfo.setItemView(null);
					} catch (CloneNotSupportedException e) {
						e.printStackTrace();
						return;
					}

					if (ShareDriveApplication.getInstance().isScrolling()) {
					} else {
						shareId = "";
						isInode = -1;
						Log.i("nnnn", fileFolderInfo.getiNodeId() + "  " + fileFolderInfo.getId());
						if (null != fileFolderInfo.getiNodeId()) {
							isInode = Constant.DOWNLOAD_STATUS_INODE;
							shareId = fileFolderInfo.getiNodeId();
						} else if (null != fileFolderInfo.getId()) {
							isInode = Constant.DOWNLOAD_STATUS_NOT_INODE;
							shareId = fileFolderInfo.getId();
						}
						if (1 == fileFolderInfo.getIsFile()) {
							final iFileManager mdmTools = FileManagerFactory.getFileManager(context);

							lastPath = DirectoryUtil.generateShareDir(context);

							if (!mdmTools.fileIsExist(lastPath)) {
								mdmTools.createFilePath(lastPath);
							}
							path = DirectoryUtil.generateShareDownloadPath(context, fileFolderInfo.getOwnerBy(), fileFolderInfo.getId(),
									fileFolderInfo.getName());

							boolean isSync = false;
							int downloadStart = Constant.DOWNLOAD_NON_UPDATE_DB;
							if (null != fileFolderInfo.getId() && null != shareDriveService) {

								FileFolderInfo $fileFolderInfo = shareDriveService.selectShareINode(fileFolderInfo.getId(), fileFolderInfo.getOwnerBy());
								if (null != $fileFolderInfo) {
									isSync = $fileFolderInfo.isSync();
									downloadStart = $fileFolderInfo.getTransStatus();
								} else if (new File(path).exists()) {
									isSync = true;
									downloadStart = Constant.DOWNLOAD_SUCCESS_UPDATE_DB;
								}
							} else if (null != fileFolderInfo.getId() && null != shareDriveService) {
								FileInfo fileInfo = shareDriveService.selectShareFile(fileFolderInfo.getId(), fileFolderInfo.getOwnerBy());
								isSync = fileInfo.isSync();
								downloadStart = fileInfo.getTransStatus();
							}
							Log.i("nnnn", path + "      path");
							Log.i("nnnn", isSync + "issync");
							Log.i("nnnn", downloadStart + "download");
							if (isSync && downloadStart == Constant.DOWNLOAD_SUCCESS_UPDATE_DB) {
								if (PublicTools.isFileType(path, Constant.MUSIC_TYPE)) {
									Log.i("nnnn", path + "      path");
									Log.i("nnnn", "run");
									Intent intent = new Intent(context, FileDownloadActivity.class);
									cloneOfFileFolderInfo.setIsInode(isInode);
									intent.putExtra(ClientConfig.FILE_FOLDER_INFO, cloneOfFileFolderInfo);
									intent.putExtra("isMusic", true);
									context.startActivity(intent);
									((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
								} else {
									mdmTools.openFile(path, fileFolderInfo.getSize());
								}
							} else {
								Log.i("xiangle",
										cloneOfFileFolderInfo.getId() + "  " + cloneOfFileFolderInfo.getiNodeId() + " " + cloneOfFileFolderInfo.getName()
												+ cloneOfFileFolderInfo.getOwnerId() + cloneOfFileFolderInfo.getSharedOwnerId());
								Intent intent = new Intent(context, FileDownloadActivity.class);
								cloneOfFileFolderInfo.setIsInode(isInode);
								intent.putExtra(ClientConfig.FILE_FOLDER_INFO, cloneOfFileFolderInfo);
								context.startActivity(intent);
								((Activity) context).overridePendingTransition(R.anim.right_in, R.anim.left_out);
							}
						} else {
							String ownerName = fileFolderInfo.getOwnerName();
							if (null != ownerName && 0 != ownerName.length()) {
								ShareDriveApplication.getInstance().setShareOwnerName(ownerName);
							}
							if (!ShareDriveApplication.getInstance().isFastDoubleClick()) {
								Message msg = new Message();
								msg.what = -1;
								msg.obj = fileFolderInfo;
								handler.sendMessage(msg);
							}
						}
					}
				}
			});
		}

		public void setFileFolderInfo(FileFolderInfo fileInformation) {
			this.fileFolderInfo = fileInformation;
		}
	}

}
